package com.estar.assistsurvy.receiver;

import java.util.List;

import com.estar.assistsurvy.service.getLocationService;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class GPSReceiver extends BroadcastReceiver {
	public static final String OPEN_ACTION="com.estar.receiver.ACTION_OPEN";
	public static final String CLOSE_ACTION="com.estar.receiver.ACTION_CLOSE";
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		String action = intent.getAction();
        if (intent.getAction().equals(OPEN_ACTION)) {
            //判断要启动的Service是否正在运行
            boolean isRunning = serviceRunState(context,
                    "com.estar.assistsurvy.service.getLocationService");
            if (!isRunning) {//Service没有运行，则启动服务
                Intent in = new Intent(context, getLocationService.class);
                if (android.os.Build.VERSION.SDK_INT >= 12) {
                    // 3.1以后设置Intent.FLAG_INCLUDE_STOPPED_PACKAGES
                    in.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                }
                context.startService(in);
            }
        }
		
	}

	/**
     * 判断指定Service运行的状态
     * @param context
     * @param className
     * @return
     */
    public static boolean serviceRunState(Context context, String className) {

        boolean isRun = false;
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(30);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className)) {
                isRun = true;
                break;
            }
        }
        return isRun;
    }
}
